<?php

namespace app\api\controller\kuyou\applet;

use app\common\model\Attachment;
use app\api\model\kuyou\applet\Customers as Customerss;
use app\api\model\kuyou\applet\Sets;
use Exception;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Shared\Date as PHPExcel_Shared_Date;
/**
 * 客户接口
 */
class Customers extends Common
{
    protected $noNeedRight = ['getDetail'];

    /**
     * 获取客户
     * @ApiMethod (POST)
     * @param int $page 页码
     * @param int $limit 每页条数
     * @param string $name 客户名称
     */
    public function index()
    {
        if ($this->request->isPost()) {
            $page = $this->request->post('page');
            $page = empty($page)?1:$page;
            $limit = $this->request->post('limit');
            $limit = empty($limit)?config('app_limit'):$limit;

            $where = [];
            $keyword = $this->request->post('keyword');
            if(!empty($keyword)){
                $where['customer_name|customer_code'] = ['like','%'.$keyword.'%'];
            }else{
                $code = $this->request->post('customer_code');
                if(!empty($code)){
                    $where['customer_code'] = ['like','%'.$code.'%'];
                }
                $name = $this->request->post('customer_name');
                if(!empty($name)){
                    $where['customer_name'] = ['like','%'.$name.'%'];
                }
            }
            $type_id = $this->request->post('customertype_id');
            if(!empty($type_id)){
                $where['customertype_id'] = $type_id;
            }
            $status = $this->request->post('status');
            if ($status==-1){
                $where['status'] = 0;
            }else if(!empty($status)){
                $where['status'] = $status;
            }
            $mobile = $this->request->post('mobile');
            if(!empty($mobile)){
                $where['customer_mobile'] = ['like','%'.$mobile.'%'];
            }

            $result = Customerss::getList($where,$page,$limit);

            if(isset($result['list']) && isset($result['count'])){
                $this->success('查询成功',$result,200);
            }else{
                $this->error('查询失败','',406);
            }
        }else{
            $this->error('请求方式错误','',250);
        }
    }

    /**
     * 获取客户详情
     * @ApiMethod (POST)
     * @param int $id 客户ID
     */
    public function getdetail()
    {
        if ($this->request->isPost()) {
            $id = $this->request->post('id');
            if(empty($id)){
                $this->error('请输入查询参数','',500);
            }
            $result = Customerss::getDetail($id);
            if($result['status']==200){
                $this->success('查询成功',$result['msg'],200);
            }else{
                $this->error($result['msg'],'',$result['status']);
            }
        }else{
            $this->error('请求方式错误','',250);
        }
    }

    /**
     * 添加客户
     * @ApiMethod (POST)
     * @param array $detail 客户数据
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            foreach ($data as $k=>$v){
                $data[$k] = is_array($v)?$v:html_entity_decode($v);
            }
            $ret = Customerss::addDetail($data);
            if($ret['status']==200){
                $this->success('添加成功',$ret['msg'],200);
            }else{
                $this->error($ret['msg'],'',$ret['status']);
            }
        }else{
            $this->error('请求方式错误','',250);
        }
    }

    /**
     * 更新客户
     * @ApiMethod (POST)
     * @param array $detail 客户数据
     */
    public function edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            foreach ($data as $k=>$v){
                $data[$k] = is_array($v)?$v:html_entity_decode($v);
            }
            $ret = Customerss::editDetail($data);
            if($ret['status']==200){
                $this->success('更新成功','',200);
            }else{
                $this->error($ret['msg'],'',$ret['status']);
            }
        }else{
            $this->error('请求方式错误','',250);
        }
    }

    /**
     * 删除客户
     * @ApiMethod (POST)
     * @param int $id 客户id
     */
    public function del()
    {
        if ($this->request->isPost()) {
            $id = $this->request->post('id');
            $ret = Customerss::delDetail($id);
            if($ret['status']==200){
                $this->success('删除成功',$ret['msg'],200);
            }else{
                $this->error($ret['msg'],'',$ret['status']);
            }
        }else{
            $this->error('请求方式错误','',250);
        }
    }

    /**
     * 导入客户
     * @ApiMethod (POST)
     * @param string $file 客户文件路径（先上传文件后直接传入文件路径）
     */
    public function import()
    {
        if ($this->request->isPost()) {
            $file = $this->request->post('file');
            $type = $this->request->post('type');
            if(empty($file)){
                $this->error('请选择上传文件','',500);
            }

            $set_time = (new Sets())::getSet('enable_time');
            $set_time = isset($set_time[0]['value'])?strtotime($set_time[0]['value']):time();

            $filePath = ROOT_PATH . 'public' . $file;
            $filePath = str_replace("\\",'/',$filePath);
            if (!is_file($filePath)) {
                $this->error('未找到上传文件，请重新上传','',500);
            }
            //实例化reader
            $ext = pathinfo($filePath, PATHINFO_EXTENSION);
            if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
                $this->error('文件格式错误，请重新上传','',500);
            }
            if ($ext === 'csv') {
                $file = fopen($filePath, 'r');
                $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
                $fp = fopen($filePath, "w");
                $n = 0;
                while ($line = fgets($file)) {
                    $line = rtrim($line, "\n\r\0");
                    $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                    if ($encoding != 'utf-8') {
                        $line = mb_convert_encoding($line, 'utf-8', $encoding);
                    }
                    if ($n == 0 || preg_match('/^".*"$/', $line)) {
                        fwrite($fp, $line . "\n");
                    } else {
                        fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                    }
                    $n++;
                }
                fclose($file) || fclose($fp);
                $reader = new Csv();
            } elseif ($ext === 'xls') {
                $reader = new Xls();
            } else {
                $reader = new Xlsx();
            }

            //加载文件
            $insert = [];
            try {
                if (!$PHPExcel = $reader->load($filePath)) {
                    $this->error('读取文件失败，请重新上传','',500);
                }
                $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
                $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
                $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
                $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
                $fields = [];
                for ($currentRow = 2; $currentRow <= 2; $currentRow++) {
                    for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                        $val = (string)$currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                        $val = str_replace('*','',$val);
                        $fields[] = (string)$val;
                    }
                }
                if(!in_array('客户编号',$fields) || !in_array('客户名称',$fields) || !in_array('客户等级',$fields)){
                    exception('数据格式错误，请重新上传');
                }

                for ($currentRow = 3; $currentRow <= $allRow; $currentRow++) {
                    $values = [];
                    for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                        $val = (string)$currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                        $values[] = is_null($val) ? '' : $val;
                    }
                    $row = array_combine($fields, $values);
                    if( !empty($row['余额日期'])){
                        $row['余额日期'] =  strtotime(gmdate('Y-m-d H:i:s',PHPExcel_Shared_Date::excelToTimeStamp($row['余额日期'])));
                    }else{
                        $row['余额日期'] =  $set_time;
                    }
                    $insert[] = $row;
                }
            } catch (Exception $exception) {
                $this->error($exception->getMessage(),'',500);
            }
            if (!$insert) {
                $this->error('未读取到有效数据，请重新上传','',500);
            }
            $params = [];
            $code = [];
            foreach ($insert as $insert_k=>$insert_v){
                if(!empty($insert_v['客户编号']) && !empty($insert_v['客户名称'])){
                    if(!in_array($insert_v['客户编号'],$code)){
                        $code[] = $insert_v['客户编号'];
                    }else{
                        $this->error('导入失败，编号'.$insert_v['客户编号'].'重复','',500);
                    }
                    $status = checkCode($insert_v['客户编号'],1);//验证编号是否合法
                    if(!$status){
                        $this->error('导入失败，编号'.$insert_v['客户编号'].'不合法','',500);
                    }
                }
            }

            $cate = [];$level = [];$saler = [];
            foreach ($insert as $insert_k=>$insert_v){
                if(empty($insert_v['客户编号']) || empty($insert_v['客户名称']) || empty($insert_v['联系人'])){
                    unset($insert[$insert_k]);
                }else{
                    if(!empty($insert_v['客户类别']) && !in_array($insert_v['客户类别'],$cate)){
                        $cate[] = $insert_v['客户类别'];
                    }
                    if(!empty($insert_v['客户等级']) && !in_array($insert_v['客户等级'],$level)){
                        $level[] = $insert_v['客户等级'];
                    }
                    if(!empty($insert_v['销售人员']) && !in_array($insert_v['销售人员'],$saler)){
                        $saler[] = $insert_v['销售人员'];
                    }
                }
            }

            $catelist = (new \app\common\model\Customertype())->where(['type_name'=>['in',$cate]])->column('id','type_name');
            $catename = (new \app\common\model\Customertype())->where(['type_name'=>['in',$cate]])->column('type_name');
            if(sizeof($catename)!=sizeof($cate)){
                foreach ($cate as $cate_k=>$cate_v){
                    if(!in_array($cate_v,$catename)){
                        $this->error('客户分类'.$cate_v.'不存在，导入失败');
                    }
                }
            }

            $levellist = (new \app\common\model\Customerlevel())->where(['name'=>['in',$level]])->column('id','name');
            $levelname = (new \app\common\model\Customerlevel())->where(['name'=>['in',$level]])->column('name');
            if(sizeof($levelname)!=sizeof($level)){
                foreach ($level as $level_k=>$level_v){
                    if(!in_array($level_v,$levelname)){
                        $this->error('客户等级'.$level_v.'不存在，导入失败');
                    }
                }
            }

            $salerlist = (new \app\common\model\StaffMember())->where(['men_code'=>['in',$saler]])->column('id','men_code');
            $salername = (new \app\common\model\StaffMember())->where(['men_code'=>['in',$saler]])->column('men_code');
            if(sizeof($salername)!=sizeof($saler)){
                foreach ($saler as $saler_k=>$saler_v){
                    if(!in_array($saler_v,$salername)){
                        $this->error('编号为'.$saler_v.'的职员不存在，导入失败');
                    }
                }
            }

            $params = [];
            $nowsp = '';
            $code = [];
            $now_code = [];
            foreach ($insert as $insert_k=>$insert_v){
                if(!empty($insert_v['客户编号']) && !empty($insert_v['客户名称'])){
                    $nowsp = $insert_k;
                    if(in_array($insert_v['客户编号'],$code)){
                        $this->error('导入失败，客户编号'.$insert_v['客户编号'].'重复');
                    }
                    $now_code[] = $insert_v['客户编号'];
                    $params[$insert_k] = [
                        'customer_code'     => $insert_v['客户编号'],
                        'customer_name'     => $insert_v['客户名称'],
                        'customertype_id'   => isset($catelist[$insert_v['客户类别']])?$catelist[$insert_v['客户类别']]:null,
                        'customerlevel_id'  => isset($levellist[$insert_v['客户等级']])?$levellist[$insert_v['客户等级']]:1,
                        'staff_member_id'   => isset($salerlist[$insert_v['销售人员']])?$salerlist[$insert_v['销售人员']]:null,

                        'account_time'      => !empty($insert_v['余额日期'])?$insert_v['余额日期']:time(),
                        'receive_account'   => $insert_v['期初应收款'],
                        'opening_prepayment'=> $insert_v['期初预收款'],
                        'need_receive_account' => round(((float)$insert_v['期初应收款']-(float)$insert_v['期初预收款']),4),
                        'identification'    => $insert_v['纳税人识别号'],
                        'deposit_bank'      => $insert_v['开户银行'],
                        'bank_number'       => $insert_v['银行账号'],

                        'connet_name'       => $insert_v['联系人'],
                        'customer_mobile'   => $insert_v['手机'],
                        'customer_phone'    => $insert_v['座机'],
                        'qq_wx_email'       => $insert_v['QQ/微信'],
                        'getgoods_address'  => $insert_v['联系地址'],
                        'note'              => $insert_v['备注'],

                        'userlist'          =>[],
                        'first'             =>0
                    ];
                }
                if(isset($params[$nowsp]['userlist']) && (!empty($insert_v['联系人']))){
                    $is_first = 0;
                    if($insert_v['首要联系人']=='是' && $params[$nowsp]['first']==0){
                        $is_first = 1;$params[$nowsp]['first'] = 1;
                    }
                    $params[$nowsp]['userlist'][] = [
                        'customers_code'        => $params[$nowsp]['customer_code'],
                        'first_connect_name'    => $insert_v['联系人'],
                        'first_connect_mobile'  => $insert_v['手机'],
                        'first_connect_phone'   => $insert_v['座机'],
                        'qq_wx_email'           => $insert_v['QQ/微信'],
                        'connect_address'       => $insert_v['联系地址'],
                        'is_first'              => $is_first,
                    ];
                }
            }

            $editstatus = isset($_POST['type'])?$_POST['type']:1;
            $edit_arr = [];
            if($editstatus==0){
                $code_s = (new \app\common\model\Customers())->where(['customer_code'=>['in',$now_code]])->value('customer_code');
                if(!empty($code_s)){
                    $this->error('导入失败，客户编号'.$code_s.'已存在');
                }
            }else{
                $code_list = (new \app\common\model\Customers())->where(['customer_code'=>['in',$now_code]])->column('id','customer_code');
                foreach ($params as $params_k=>$params_v){
                    if(isset($code_list[$params_v['customer_code']])){
                        $params_v['id'] = $code_list[$params_v['customer_code']];
                        $edit_arr[] = $params_v;
                        unset($params[$params_k]);
                    }
                }
            }

            $ret = Customerss::import($params,$edit_arr);
            if($ret['status']==200){

                //导入成功删除文件
                $file = $this->request->post('file');
                $attachment = (new Attachment())->where(['url'=>$file])->find();
                if($attachment){
                    \think\Hook::add('upload_delete', function ($attachment) {
                        if ($attachment['storage'] == 'local') {
                            $attachmentFile = ROOT_PATH . '/public' . $attachment['url'];
                            if (is_file($attachmentFile)) {
                                @unlink($attachmentFile);
                            }
                        }
                    });
                    \think\Hook::listen("upload_delete", $attachment);
                    (new Attachment())->where(['url'=>$file])->delete();
                }

                $this->success('导入成功','',200);
            }else{
                $this->error($ret['msg'],'',$ret['status']);
            }
        }else{
            $this->error('请求方式错误','',250);
        }
    }
}
